package com.huluobo.a2202kotlindouyindemo.home

import androidx.lifecycle.MutableLiveData
import com.huluobo.base.bean.SearchBeanResult
import com.huluobo.base.bean.VideoBean
import com.huluobo.base.bean.VideoBeanResult
import com.huluobo.base.model.BaseRepo
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
 *  Created by LC on 2024/6/7.
 */
class HomeRepo : BaseRepo() {
    fun getVideoList(
        currentPage: Int,
        pageSize: Int,
        success: MutableLiveData<VideoBeanResult>,
        failed: MutableLiveData<String>
    ) {
        apiService.getVideos(currentPage, pageSize)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<VideoBeanResult> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onError(e: Throwable) {
                    failed.value = e.message
                }

                override fun onComplete() {
                }

                override fun onNext(t: VideoBeanResult) {
                    success.value = t
                }
            })
    }

    fun findVideos(keywords: String, success: MutableLiveData<VideoBeanResult>, failed: MutableLiveData<String>) {
        apiService.findVideos(keywords)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<VideoBeanResult> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onError(e: Throwable) {
                    failed.value = e.message
                }

                override fun onComplete() {
                }

                override fun onNext(t: VideoBeanResult) {
                    success.value = t
                }
            })
    }

    fun saveSearch(searchBeanResult: SearchBeanResult) {
        db.getSearchDao().insertKeywords(searchBeanResult)
    }

    fun querySearch(success: MutableLiveData<List<SearchBeanResult>>, failed: MutableLiveData<String>) {
        db.getSearchDao().queryKeywords()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<List<SearchBeanResult>> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onError(e: Throwable) {
                    failed.value = e.message
                }

                override fun onComplete() {
                }

                override fun onNext(t: List<SearchBeanResult>) {
                    success.value = t
                }
            })
    }
}